package logger

import (
	"gitee.com/DonHz/qimi/bluebell/config"
	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

func Init(cfg *config.LogConfig, mode string) error {
	encoderConfig:=zapcore.EncoderConfig{
		TimeKey:        "time",
		LevelKey:       "level",
		NameKey:        "Logger",
		CallerKey:      "caller",
		FunctionKey:    zapcore.OmitKey,
		MessageKey:     "msg",
		StacktraceKey:  "stacktrace",
		LineEnding:     zapcore.DefaultLineEnding,
		EncodeLevel:    zapcore.CapitalLevelEncoder,
		EncodeTime:     zapcore.ISO8601TimeEncoder,
		EncodeDuration: zapcore.SecondsDurationEncoder,
		EncodeCaller:   zapcore.ShortCallerEncoder,
	}
	//encoder := zapcore.NewJSONEncoder(encoderConfig)
	encoder := zapcore.NewConsoleEncoder(encoderConfig)
	writeSyncer:= getLoggerWriter(cfg)
	var l = new(zapcore.Level)
	err := l.UnmarshalText([]byte(cfg.Level))
	if err!=nil {
		return err
	}

	var core zapcore.Core
	if mode=="dev" {
		consoleEncoder:=zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
		core = zapcore.NewTee(
			zapcore.NewCore(encoder, writeSyncer, l),
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel),
		)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, l)
	}
	logger := zap.New(core, zap.AddCaller())
	// 替换zap库全局的logger
	zap.ReplaceGlobals(logger)
	return nil
}

func getLoggerWriter(cfg *config.LogConfig) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename: cfg.Filename,
		MaxSize: cfg.MaxSize,	// M
		MaxBackups: cfg.MaxBackups, // 备份数量
		MaxAge: cfg.MaxAge, // 保存天数
		Compress: cfg.Compress,	// 是否压缩
	}
	return zapcore.AddSync(lumberJackLogger)
}